package com.heima.behavior.service.impl;

import com.heima.behavior.service.*;
import com.heima.common.constants.user.UserRelationConstants;
import com.heima.model.behavior.dtos.ArticleBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.thread.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class ApArticleBehaviorServiceImpl implements ApArticleBehaviorService {
    @Resource
    ApBehaviorEntryService behaviorEntryService;
    @Resource
    ApCollectionBehaviorService collectionBehaviorService;
    @Resource
    ApLikesBehaviorService likesBehaviorService;
    @Resource
    ApReadBehaviorService readBehaviorService;
    @Resource
    ApUnlikeBehaviorService unlikeBehaviorService;
    @Autowired
    StringRedisTemplate redisTemplate;


    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDTO dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        Map<String, Boolean> map = new HashMap<>();
        if (user == null || user.getId()==null){
            map.put("isfollow",false);
            map.put("islike",false);
            map.put("isunlike",false);
            map.put("iscollection",false);
            return ResponseResult.okResult(map);
        }
        try {
            Integer userId = user.getId();
            ApBehaviorEntry behaviorEntry = behaviorEntryService.findByUserIdOrEquipmentId(userId, null);
            ZSetOperations opsForZSet = redisTemplate.opsForZSet();
            Double score = opsForZSet.score(UserRelationConstants.FOLLOW_LIST + userId, dto.getAuthorApUserId().toString());
            log.info("score:{}, userId:{}, dto.getAuthorApUserId(): {}",score,userId,dto.getAuthorApUserId());
            map.put("isfollow",score != null);
            map.put("islike",likesBehaviorService.check(behaviorEntry,dto.getArticleId()));
            map.put("isunlike",unlikeBehaviorService.check(behaviorEntry,dto.getArticleId()));
            map.put("iscollection",collectionBehaviorService.check(behaviorEntry,dto.getArticleId()));
            return ResponseResult.okResult(map);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}
